package com.gjw.designpattern.proxy.dynamicProxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * 动态代理  （基于cglib的动态代理   通过类来实现动态代理）
 */
public class Client2 {

    public void test(){
        System.out.println("测试");
    }

    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();
        //设置代理类
        enhancer.setSuperclass(Client2.class);
        //这一步可以将创建一个类来实现 MethodInterceptor
        //然后将创建的类传入setCallback
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                System.out.println("before");
                methodProxy.invokeSuper(o,objects);
                System.out.println("end");
                return o;
            }
        });
        //生成代理对象
        Client2 client = (Client2) enhancer.create();
        client.test();
    }
}
